package com.ttdevs.socket.tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.BlockingQueue;

import com.ttdevs.socket.ISocket;
import com.ttdevs.socket.util.BaseThread;

public class TCPSender extends BaseThread {
	private ISocket mSocket;
	private OutputStream out;
	private BlockingQueue<byte[]> mSenderQueue;

	public TCPSender(BlockingQueue<byte[]> senderQueue, ISocket socket, OutputStream out) {
		mSocket = socket;
		mSenderQueue = senderQueue;
		this.out = out;
	}

	@Override
	public boolean prepare() {
		if (mSocket == null || mSenderQueue == null || out == null) {
			return false;
		}
		return super.prepare();
	}

	@Override
	public void execute() {
		try {
			byte[] data = mSenderQueue.take();
			out.write(data);
		} catch (InterruptedException e) {
			e.printStackTrace();
			notifyError();
		} catch (IOException e) {
			e.printStackTrace();
			notifyError();
		}
	}

	private void notifyError() {
		mSocket.close(true, true);
		this.quit();
	}

}
